package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @version 1.0
 * @Author yanjingren
 * @Date 2021/6/17
 * @Description com.atguigu.gulimall.ssoserver.controller
 */
@Controller
public class LoginController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam("token") String token) {
        return stringRedisTemplate.opsForValue().get(token);
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model, @CookieValue(value = "sso_token", required = false) String ssoToken) {
        if (!StringUtils.isEmpty(ssoToken)) {
            // 说明之前有人登陆过，留下了痕迹，直接返回之前页面
            return "redirect:" + url + "?token=" + ssoToken;
        }
        model.addAttribute("url", url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {
        // 登录成功要跳转，跳回到之前的页面
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            // 把登录成功的用户保存起来
            String s = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(s, username);

            Cookie sso_token = new Cookie("sso_token", s);
            response.addCookie(sso_token);

            return "redirect:" + url + "?token=" + s;
        }
        // 登录失败，展示登录页
        return "login";
    }

}
